<!--
 * @Descripttion: 
 * @LastEditors: xzh
 * @LastEditTime: 2024-05-05 20:34:50
-->
<template>
  <el-scrollbar v-loading="loading">
    <div
      :id="'chartItem_' + chart.id"
      :key="chart.id"
      class="chart-item"
      :style="{
        height,
        border: !!border ? '1px solid var(--el-border-color)' : '',
      }"
    />
  </el-scrollbar>
</template>

<script setup lang="ts">
import Dile_StoreAction from "@/utils/cache/store";
import { object_Inf } from "@/utils/typings/index.type";
import { ref, reactive, onMounted, onUnmounted, nextTick, inject } from "vue";
const emit = defineEmits(["click"]);
const props = defineProps({
  chart: {
    type: Object,
    required: true,
    default: {},
  },
  height: {
    type: String,
    required: false,
    default: "100%",
  },
  border: {
    type: Boolean,
    required: false,
    default: false,
  },
  loading: {
    type: Boolean,
    requited: false,
    default: false,
  },
});
/**
 * @Author: xzh
 * @Descripttion: 图表实例
 * @Param:
 */
let echarts = reactive<any>(inject("echarts"));
/**
 * @Author: xzh
 * @Descripttion: 报表参数
 * @Param:
 */
let chartItemParam = reactive<any>({
  chartRef: null,
});

onMounted(() => {
  let { chart } = props;
  Object.keys(chart).length > 0 && init();
});

/**
 * @Author: xzh
 * @Descripttion: 初始化
 * @Param:
 */
let init = () => {
  initLineChart();
  window.addEventListener("resize", handleResize);
};
/**
 * @Author: xzh
 * @Descripttion:销毁前初始化
 * @Param:
 */
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  chartItemParam = null;
});
/**
 * @Author: xzh
 * @Descripttion:监听尺寸
 * @Param:
 */
let handleResize = () => {
  let { chartRef } = chartItemParam;
  chartRef.resize();
};
/**
 * @Author: xzh
 * @Descripttion: 加载图表数据
 * @Param:
 */
let initLineChart = async () => {
  await nextTick();
  let { id, option } = props.chart,
    //获取当前环境
    { theme } = Dile_StoreAction.getNavbar();

  var chartDom: any = document.querySelector(`#chartItem_${id}`)!;
  let chartRef = echarts.init(chartDom, theme);
  chartRef.setOption({
    ...option,
    backgroundColor: "transparent",
  });
  Object.assign(chartItemParam, {
    chartRef,
  });
  // 为饼图添加点击事件
  chartRef.on("click", (params: object_Inf) => {
    emit("click", params);
  });
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped></style>
